<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dify 智能助手</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus"></script>
    <!-- 先加载 Dify 配置 -->
    <script>
        // 设置 Dify 配置
        // 确保在加载 Dify 脚本前设置配置
        (function() {
            // 如果已经存在配置，则合并
            window.difyChatbotConfig = window.difyChatbotConfig || {};
            
            // 设置默认配置
            const defaultConfig = {
                token: 'BxhavBlf7yvnctQI',
                baseUrl: 'https://udify.app',
                // 其他可选配置
                theme: {
                    primaryColor: '#409EFF',
                    primaryTextColor: '#303133',
                    borderRadius: '8px',
                    boxShadow: '0 2px 12px 0 rgba(0, 0, 0, 0.1)'
                },
                // 添加更多默认配置
                features: {
                    header: true,
                    footer: true,
                    input: true
                }
            };
            
            // 合并配置
            Object.assign(window.difyChatbotConfig, defaultConfig);
            
            console.log('Dify 配置已加载:', window.difyChatbotConfig);
        })();
    </script>
    <!-- 然后加载 Dify 脚本 -->
    <script src="https://udify.app/embed.min.js" defer></script>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background-color: #f5f7fa;
            overflow: hidden;
        }
        #app {
            height: 100vh;
            width: 100%;
            max-width: 100vw;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            box-sizing: border-box;
            overflow: hidden;
        }
        .header {
            background-color: #409EFF;
            color: white;
            padding: 10px 16px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            position: sticky;
            top: 0;
            flex-shrink: 0;
        }
        .header h1 {
            margin: 0;
            font-size: 16px;
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            width: 100%;
            height: 100%;
            padding: 0;
            margin: 0;
            box-sizing: border-box;
            overflow: hidden;
        }
        .chat-wrapper {
            flex: 1;
            background: white;
            border-radius: 0;
            box-shadow: none;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
        .chat-iframe {
            flex: 1;
            border: none;
            width: 100%;
            height: 0%;
            min-height: 0;
            margin: 0;
            padding: 0;
            display: block;
        }
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            color: #909399;
        }
        .error-message {
            text-align: center;
            padding: 20px;
            color: #f56c6c;
        }
        .retry-btn {
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="header">
            <h1>Dify 智能助手</h1>
        </div>
        <div class="chat-container">
            <div class="chat-wrapper">
                <!-- 使用 Web Component 方式 -->
                
                
                <!-- 备用 iframe 方式 -->
                <iframe 
                    v-if="showIframe"
                    src="https://udify.app/chat/BxhavBlf7yvnctQI"
                    class="chat-iframe"
                    sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
                    @load="onIframeLoad"
                    @error="onIframeError">
                </iframe>
                
                <div v-if="error" class="error-message">
                    <p>加载 Dify 聊天机器人时出错：{{ error }}</p>
                    <el-button type="primary" class="retry-btn" @click="retryLoad">重试</el-button>
                </div>
                
                <div v-if="loading" class="loading">
                    <el-icon class="is-loading" style="margin-right: 8px;"><Loading /></el-icon>
                    <span>正在加载 Dify 聊天机器人...</span>
                </div>
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref, onMounted } = Vue;
        
        createApp({
            setup() {
                const loading = ref(true);
                const error = ref('');
                const showIframe = ref(false);
                
                const initDifyChatbot = () => {
                    try {
                        // 确保 Dify 脚本已加载
                        if (window.difyChatbotConfig && window.customElements && window.customElements.get('dify-chatbot')) {
                            const container = document.getElementById('dify-chatbot-container');
                            if (container) {
                                // 清空容器
                                container.innerHTML = '';
                                // 创建新的 Dify 聊天机器人实例
                                const difyBot = document.createElement('dify-chatbot');
                                difyBot.setAttribute('chatflow-id', 'BxhavBlf7yvnctQI');
                                container.appendChild(difyBot);
                                
                                // 监听 Dify 聊天机器人加载完成事件
                                difyBot.addEventListener('ready', () => {
                                    console.log('Dify 聊天机器人已加载');
                                    loading.value = false;
                                });
                                
                                return true;
                            }
                        }
                        return false;
                    } catch (err) {
                        console.error('初始化 Dify 聊天机器人时出错:', err);
                        return false;
                    }
                };
                
                const onIframeLoad = () => {
                    loading.value = false;
                    error.value = '';
                };
                
                const onIframeError = (e) => {
                    console.error('Failed to load Dify iframe:', e);
                    loading.value = false;
                    error.value = '无法加载 Dify 聊天界面，请检查网络连接';
                };
                
                const retryLoad = () => {
                    error.value = '';
                    loading.value = true;
                    if (!initDifyChatbot()) {
                        showIframe.value = true;
                    }
                };
                
                // 检查 Web Component 是否加载成功
                onMounted(() => {
                    // 先尝试初始化 Dify 聊天机器人
                    if (!initDifyChatbot()) {
                        // 如果初始化失败，等待 Dify 脚本加载完成
                        const checkDifyLoaded = setInterval(() => {
                            if (window.difyChatbotConfig && document.readyState === 'complete') {
                                clearInterval(checkDifyLoaded);
                                if (!initDifyChatbot()) {
                                    console.log('Web Component 初始化失败，切换到 iframe 方式');
                                    showIframe.value = true;
                                }
                            }
                        }, 500);
                        
                        // 5秒后超时
                        setTimeout(() => {
                            clearInterval(checkDifyLoaded);
                            if (loading.value) {
                                console.log('Web Component 加载超时，切换到 iframe 方式');
                                showIframe.value = true;
                            }
                        }, 5000);
                    }
                    
                    // 监听 Dify 脚本加载错误
                    document.addEventListener('error', function(e) {
                        const target = e.target;
                        if (target.tagName === 'SCRIPT' && target.src && target.src.includes('udify.app')) {
                            console.error('Dify 脚本加载失败:', e);
                            error.value = 'Dify 脚本加载失败，请刷新页面重试';
                            loading.value = false;
                        }
                    }, true);
                });
                
                return {
                    loading,
                    error,
                    showIframe,
                    onIframeLoad,
                    onIframeError,
                    retryLoad
                };
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>
